﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace SMARTMobile.WinPhone
{
    public static class XmlHelper
    {
        //public static IEnumerable<T> GetItems<T>(XmlReader reader, string elementName) where T : class
        //{
        //    XmlSerializer rssItemSerializer = new XmlSerializer(typeof(T));
        //    while (reader.GoToElement(elementName))
        //    {
        //        var item = rssItemSerializer.Deserialize(reader) as T;
        //        Debug.WriteLine(item);
        //        yield return item;
        //    }
        //}

        public static T GetItem<T>(XElement element, string elementName)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            XmlReader reader = element.CreateReader();
            while (reader.GoToElement(elementName))
            {
                var item = (T)serializer.Deserialize(reader);
                Debug.WriteLine(item);
                return item;
            }

            return default(T);
        }

        public static IEnumerable<T> GetItems<T>(XElement element, string elementName) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            XmlReader reader = element.CreateReader();
            while (reader.GoToElement(elementName))
            {
                var item = (T)serializer.Deserialize(reader);
                Debug.WriteLine(item);
                yield return item;
            }
        }

        public static bool GoToElement(this XmlReader reader, string elementName)
        {
            do
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == elementName)
                {
                    return true;
                }
            }
            while (reader.Read());

            // not found
            return false;
        }
    }
}
